from apps import db
from datetime import datetime

class BaseModel(db.Model):
    __abstract__ = True
    
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now())
    updated_at = db.Column(db.DateTime, onupdate=datetime.now())
    is_active = db.Column(db.Boolean, nullable=False, default=True)

    def to_dict(self, exclude_fields=None):
        if exclude_fields is None:
            exclude_fields = []
            
        columns = self.__table__.columns
        return {
            column.name: getattr(self, column.name) if not isinstance(getattr(self, column.name), datetime) 
                else self.datetime_to_str(getattr(self, column.name))
            for column in columns
            if column.name not in exclude_fields
        }

    def add(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def update(self, **kwargs):
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.commit()

    @classmethod
    def get_by_id(cls, id):
        return cls.query.get(id)
    
    def datetime_to_str(self, datetime_obj):
        return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')